package 面试;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyEResource{
    private volatile boolean flag = true;
    private AtomicInteger atomicInteger = new AtomicInteger();
    BlockingQueue<String> blockingQueue = null;

    public MyEResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());
    }

    public void myProd() throws Exception {
        String data = null;
        boolean retValue;
        while (flag){
            data = atomicInteger.incrementAndGet()+"";
            retValue = blockingQueue.offer(data,2l, TimeUnit.SECONDS);
            if(retValue){
                System.out.println(Thread.currentThread().getName() + "\t插入"+data+"成功");
            }else {
                System.out.println(Thread.currentThread().getName() + "\t插入"+data+"失败");
            }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().getName()+ "\t老板叫停,表示flag = false,生产动作结束");
    }

    public void myConsumer() throws Exception {
        String result = null;
        while (flag){
            result = blockingQueue.poll(2l, TimeUnit.SECONDS);
            if(null == result || result.equalsIgnoreCase("")){
                flag = false;
                System.out.println(Thread.currentThread().getName() + "\t超过两秒没有取出蛋糕，退出");
                System.out.println();
                System.out.println();
                return;
            }
            System.out.println(Thread.currentThread().getName() + "消费蛋糕" + result + "成功");
        }
    }

    public void stop(){
        this.flag = false;
    }
}


public class ProdConsumer_BlockingQueue {

    public static void main(String[] args) {
        MyEResource myEResource = new MyEResource(new ArrayBlockingQueue<>(10));

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t生产线程启动");
            try {
                myEResource.myProd();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"Prod").start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t消费线程启动");
            System.out.println();
            System.out.println();
            System.out.println();
            try {
                myEResource.myConsumer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"Consumer").start();

        try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {e.printStackTrace(); }
        System.out.println();
        System.out.println();
        System.out.println();

        System.out.println("5秒钟到，main线程叫停，活动结束");

        myEResource.stop();
    }
}